package com.huixi.microspur.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huixi.microspur.web.mapper.WjUserMapper;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppeal;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppealEndorse;
import com.huixi.microspur.web.pojo.entity.dynamic.WjDynamic;
import com.huixi.microspur.web.pojo.entity.user.WjUser;
import com.huixi.microspur.web.pojo.entity.user.WjUserWx;
import com.huixi.microspur.web.pojo.vo.user.UserDataVO;
import com.huixi.microspur.web.service.*;
import com.huixi.microspur.web.util.CommonUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author xzl
 * @since 2020-01-17
 */
@Service
public class WjUserServiceImpl extends ServiceImpl<WjUserMapper, WjUser> implements WjUserService {

    @Resource
    private WjUserService wjUserService;

    @Resource
    private WjAppealService wjAppealService;

    @Resource
    private WjDynamicService wjDynamicService;

    @Resource
    private WjAppealEndorseService wjAppealEndorseService;

    @Resource
    private WjUserWxService wjUserWxService;

    @Resource
    private WxMaService wxMaService;

    /**
     * 获取session_key
     *
     * @param code 用户code
     * @return java.lang.String
     * @Author 李辉
     * @Date 2019/11/23 4:31
     **/
    @SneakyThrows
    @Override
    public WxMaJscode2SessionResult getWxSession(String code) {
        return wxMaService.getUserService().getSessionInfo(code);
    }


    /**
     * 获取用户加密信息 并且保存
     *
     * @param
     * @return void
     * @Author 李辉
     * @Date 2019/11/23 4:33
     **/
    @Override
    public WxMaUserInfo getEncryptionUserInfo(String encryptedData, String session_key, String ivKey) {
        // 返回加密的数据
        return wxMaService.getUserService().getUserInfo(session_key, encryptedData, ivKey);
    }

    /**
     * 根据用户code 获取用户的 openId 和 sessionKey , 来确定有没有授权过。 如果授权发放用户信息 ，没有就创建一个用户
     *
     * @param code 用户小程序的code
     * @return WjUser 用户信息
     * @Author 叶秋
     * @Date 2020/2/1 20:17
     **/
    @Override
    public WjUser detectionUserAuthorization(String code) {
        WxMaJscode2SessionResult wxSessionKey = getWxSession(code);

        // 根据open_id 检测数据库中是否有此用户
        QueryWrapper<WjUserWx> wjUserWxQueryWrapper = new QueryWrapper<>();
        wjUserWxQueryWrapper.eq("wx_open_id", wxSessionKey.getOpenid());
        WjUserWx wjUserWx = wjUserWxService.getOne(wjUserWxQueryWrapper);

        if (ObjectUtil.isNotNull(wjUserWx)) {
            return wjUserService.getById(wjUserWx.getUserId());
        }

        // 检测用户不存在的情况 随机创建用户资料
        WjUser wjUser = CommonUtil.randomCreateUserInfo();
        WjUserWx newWjUserWx = new WjUserWx().setUserId(wjUser.getUserId())
                .setWxOpenId(wxSessionKey.getOpenid());

        boolean save = wjUserService.save(wjUser);
        boolean save1 = wjUserWxService.save(newWjUserWx);

        return wjUser;

    }

    /**
     * 根据用户id 查询用户信息 包括需要查询其他表的一些数据（诉求、动态...）
     *
     * @param userId
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/1 21:55
     **/
    @Override
    public UserDataVO getByIdUserData(String userId) {
        WjUser byId = wjUserService.getById(userId);
        UserDataVO userDataVO = new UserDataVO();
        BeanUtil.copyProperties(byId, userDataVO);

        // 查询诉求 数量
        QueryWrapper<WjAppeal> wjAppealQueryWrapper = new QueryWrapper<>();
        wjAppealQueryWrapper.eq("user_id", userId);
        int appealCount = wjAppealService.count(wjAppealQueryWrapper);
        userDataVO.setAppealCount(appealCount);

        // 查询动态 数量
        QueryWrapper<WjDynamic> wjDynamicQueryWrapper = new QueryWrapper<>();
        wjDynamicQueryWrapper.eq("user_id", userId);
        int dynamicCount = wjDynamicService.count(wjDynamicQueryWrapper);
        userDataVO.setDynamicCount(dynamicCount);

        QueryWrapper<WjAppealEndorse> wjAppealEndorseQueryWrapper = new QueryWrapper<>();
        wjAppealEndorseQueryWrapper.eq("user_id", userId);
        int endorseCount = wjAppealEndorseService.count(wjAppealEndorseQueryWrapper);
        userDataVO.setEndorseCount(endorseCount);

        return userDataVO;
    }

}
